﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using SDLITS.Common;
using SDLITS.Model;
using System.Security.Cryptography;
using System.Text;
using System.Web.Script.Serialization;
using MySoft.Data;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.IO;

namespace SDLITS.Web
{
    /// <summary>
    /// WebService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://sdlits.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    // [System.Web.Script.Services.ScriptService]
    public class WebService : System.Web.Services.WebService
    {
        /// <summary>
        /// 与ASP兼容的MD5加密算法
        /// </summary>
        public string GetMD5(string s, string encodingCharset)
        {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] t = md5.ComputeHash(Encoding.GetEncoding(encodingCharset).GetBytes(s));
            StringBuilder sb = new StringBuilder(32);
            for (int i = 0; i < t.Length; i++)
            {
                sb.Append(t[i].ToString("x").PadLeft(2, '0'));
            }
            return sb.ToString();
        }
        #region 会员
        private string UserStatus(string MemcardNo, string Password)
        {
            V_MemCardInfoType mem = SDDbSession.Default.From<V_MemCardInfoType>().Where(V_MemCardInfoType._.MemCardNo == MemcardNo).ToFirst();
            if (mem != null)
            {
                try
                {
                    string str = mem.IDNumber.Substring(mem.IDNumber.Length - 6);
                    if (GetMD5(str, "utf-8") == Password)
                    {
                        return "200";
                    }
                    else
                    { return "501"; }
                }
                catch (Exception) { return "501"; }
            }
            else
            { return "500"; }
        }
        #endregion

        #region 会员验证接口
        [WebMethod]
        public string UserAudit(string memcardno, string password)
        {
            string s = UserStatus(memcardno, password);
            if (s == "200")
            {
                V_MemCardInfoType mem = SDDbSession.Default.From<V_MemCardInfoType>().Where(V_MemCardInfoType._.MemCardNo == memcardno).ToFirst();
                string json = "{\"status\":\"200\", \"result\":{\"memcardno\":\"" + memcardno + "\",\"mobile\":[\"" + mem.Cell + "\"] }}";
                return json;
            }
            else if (s == "501")
            { return "{\"stutus\":\"501\"}"; }
            else
            { return "{\"stutus\":\"500\"}"; }
        }
        #endregion

        #region 会员搜索接口
        [WebMethod]
        public string ContactSearch(string memcardno, string password, string destmemcardno, string destname)
        {
            string s = UserStatus(memcardno, password);
            if (s == "200")
            {
                WhereClip wc = WhereClip.All;
                if (!string.IsNullOrEmpty(destmemcardno))
                {
                    wc = wc && V_MemCardInfoType._.MemCardNo == destmemcardno;
                }
                if (!string.IsNullOrEmpty(destname))
                {
                    wc = wc && V_MemCardInfoType._.Name.Contain(destname);
                }
                List<V_MemCardInfoType> list = SDDbSession.Default.From<V_MemCardInfoType>().Where(wc).ToList();
                List<ContactSearch> items = new List<ContactSearch>();
                if (list.Count > 0)
                {
                    foreach (var li in list)
                    {
                        ContactSearch cs = new ContactSearch();
                        cs.loginid = li.MemCardNo;
                        cs.memcardno = li.MemCardNo;
                        cs.place = li.IDAddress;
                        cs.realname = li.Name;
                        cs.sex = string.IsNullOrEmpty(li.Sex.ToString()) ? "男" : (Convert.ToBoolean(li.Sex) ? "男" : "女");
                        items.Add(cs);
                    }
                }
                JavaScriptSerializer js = new JavaScriptSerializer();
                string json = js.Serialize(items);
                return "{\"status\":\"200\", \"result\":" + json + "}";
            }
            else
            { return "{\"stutus\":\"500\"}"; }
        }
        #endregion

        #region 会员查询接口
        [WebMethod]
        public string ContactGet(string memcardno, string password, string destmemcardno)
        {
            string s = UserStatus(memcardno, password);
            if (s == "200")
            {
                WhereClip wc = WhereClip.All;
                if (!string.IsNullOrEmpty(destmemcardno))
                {
                    wc = wc && V_MemCardInfoType._.MemCardNo == destmemcardno;
                }
                V_MemCardInfoType list = SDDbSession.Default.From<V_MemCardInfoType>().Where(wc).ToFirst();
                ContactSearch cs = new ContactSearch();
                if (list != null)
                {
                    cs.loginid = list.MemCardNo;
                    cs.memcardno = list.MemCardNo;
                    cs.place = list.IDAddress;
                    cs.realname = list.Name;
                    cs.sex = string.IsNullOrEmpty(list.Sex.ToString()) ? "男" : (Convert.ToBoolean(list.Sex) ? "男" : "女");

                }
                JavaScriptSerializer js = new JavaScriptSerializer();
                string json = js.Serialize(cs);
                return "{\"status\":\"200\", \"result\":" + json + "}";
            }
            else
            { return "{\"stutus\":\"500\"}"; }
        }
        #endregion

        #region 货物查询接口
        [WebMethod]
        public string GoodsQuery(string memcardno, string password, string skipcount, string pagesize, string fromprovince, string fromcity, string fromregion, string toprovince, string tocity, string toregion, string carlength, string tonmin, string tonmax, string volmin, string volmax)
        {
            string s = UserStatus(memcardno, password);
            if (s == "200")
            {
                #region 条件
                WhereClip wc = WhereClip.All;
                if (!string.IsNullOrEmpty(fromprovince))
                {
                    wc = wc && V_LEDMessgeRegion._.StartTopRegionName == fromprovince;
                }
                if (!string.IsNullOrEmpty(fromcity))
                {
                    wc = wc && V_LEDMessgeRegion._.StartParentRegionName == fromcity;
                }
                if (!string.IsNullOrEmpty(fromregion))
                {
                    wc = wc && V_LEDMessgeRegion._.StartRegionName == fromregion;
                }
                if (!string.IsNullOrEmpty(toprovince))
                {
                    wc = wc && V_LEDMessgeRegion._.EndTopRegionName == toprovince;
                }
                if (!string.IsNullOrEmpty(tocity))
                {
                    wc = wc && V_LEDMessgeRegion._.EndParentRegionName == tocity;
                }
                if (!string.IsNullOrEmpty(toregion))
                {
                    wc = wc && V_LEDMessgeRegion._.EndRegionName == toregion;
                }
                if (!string.IsNullOrEmpty(carlength))
                {
                    wc = wc && V_LEDMessgeRegion._.CarInfo == carlength;
                }
                if (!string.IsNullOrEmpty(tonmax))
                {
                    wc = wc && V_LEDMessgeRegion._.Amount <= tonmax && V_LEDMessgeRegion._.UnitType == "吨";
                }
                if (!string.IsNullOrEmpty(tonmin))
                {
                    wc = wc && V_LEDMessgeRegion._.Amount >= tonmin && V_LEDMessgeRegion._.UnitType == "吨";
                }
                if (!string.IsNullOrEmpty(volmax))
                {
                    wc = wc && V_LEDMessgeRegion._.Amount <= volmax && V_LEDMessgeRegion._.UnitType == "立方";
                }
                if (!string.IsNullOrEmpty(volmin))
                {
                    wc = wc && V_LEDMessgeRegion._.Amount >= volmin && V_LEDMessgeRegion._.UnitType == "立方";
                }
                #endregion
                double skip = 0;
                double page = 0;
                double.TryParse(skipcount, out skip);
                double.TryParse(pagesize, out page);
                List<V_LEDMessgeRegion> list = SDDbSession.Default.From<V_LEDMessgeRegion>().Where(wc).Page(Convert.ToInt32(page), Convert.ToInt32(Math.Floor(skip / page) + 1)).ToList();
                List<GoodsQuery> items = new List<GoodsQuery>();
                if (list.Count > 0)
                {
                    foreach (var li in list)
                    {
                        GoodsQuery cs = new GoodsQuery();
                        cs.carlengthrequire = li.CarInfo.ToString();
                        cs.description = "";
                        cs.elescreennumber = li.RoomName;
                        cs.fromcity = li.StartParentRegionName;
                        cs.fromprovince = li.StartTopRegionName;
                        cs.fromregion = li.StartRegionName;
                        cs.goodsname = li.GoodName;
                        cs.goodsvolume = li.Amount.ToString();
                        cs.goodsweight = li.Amount.ToString();
                        cs.ntransmoney = "";
                        cs.releasedate = li.CreateDate.ToString();
                        cs.tocity = li.EndParentRegionName;
                        cs.toprovince = li.EndTopRegionName;
                        cs.toregion = li.EndRegionName;
                        cs.trademobilenumber = "";
                        items.Add(cs);
                    }

                    JavaScriptSerializer js = new JavaScriptSerializer();
                    string json = js.Serialize(items);
                    return "{\"status\":\"200\", \"result\":" + json + "}";
                }
                else
                {
                    return "{\"stutus\":\"503\"}";
                }
            }
            else if (s == "501")
            { return "{\"stutus\":\"501\"}"; }
            else
            { return "{\"stutus\":\"500\"}"; }
        }
        #endregion

        #region 一卡通余额接口
        private string AccountBalance(string memcardno, string password)
        {
            V_MemCardInfoType mem = SDDbSession.Default.From<V_MemCardInfoType>().Where(V_MemCardInfoType._.MemCardNo == memcardno).ToFirst();
            if (mem != null)
            {
                try
                {
                    string str = mem.IDNumber.Substring(mem.IDNumber.Length - 6);
                    if (GetMD5(str, "utf-8") == password)
                    {
                        if (!string.IsNullOrEmpty(mem.LeftCash.ToString()))
                        {
                            string amount = mem.LeftCash.ToString();
                            return "{\"stutus\":\"200\",\"result\":{\"memcardno\":\"" + memcardno + "\",\"amount\":\"" + amount + "\"}}";
                        }
                        else
                        {
                            { return "{\"stutus\":\"502\"}"; }
                        }
                    }
                    else
                    { return "{\"stutus\":\"501\"}"; }
                }
                catch (Exception) { return "{\"stutus\":\"501\"}"; }
            }
            else
            { return "{\"stutus\":\"500\"}"; }
        }
        #endregion

        #region 充值查询接口
        [WebMethod]
        public string AccountCharged(string memcardno, string password, string startdate, string enddate)
        {
            string s = UserStatus(memcardno, password);
            if (s == "200")
            {
                SqlParameter[] sp = new SqlParameter[]{
                    new SqlParameter("@CreateUserID",""),
                    new SqlParameter("@MemcardNo",memcardno),
                    new SqlParameter("@StartDate",startdate),
                    new SqlParameter("@EndDate",enddate),
                    new SqlParameter("@SPAction","SelectByDateRange")
                };
                DataSet ds = SDDbSession.Default.FromProc("TableCardRevenue").AddParameter(sp).ToDataSet();
                List<AccountCharged> items = new List<AccountCharged>();
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        AccountCharged ac = new AccountCharged();
                        ac.costamount = ds.Tables[0].Rows[i]["PlusAmount"].ToString();
                        ac.inputdate = ds.Tables[0].Rows[i]["CreateDate"].ToString();
                        ac.memcardno = memcardno;
                        items.Add(ac);
                    }
                }
                JavaScriptSerializer js = new JavaScriptSerializer();
                string json = js.Serialize(items);
                return "{\"status\":\"200\", \"result\":" + json + "}";
            }
            else if (s == "500")
            { return "{\"stutus\":\"500\"}"; }
            else
            { return "{\"stutus\":\"501\"}"; }
        }
        #endregion

        #region 消费记录查询接口
        [WebMethod]
        public string AccountHistory(string memcardno, string password, string startdate, string enddate)
        {
            string s = UserStatus(memcardno, password);
            if (s == "200")
            {
                WhereClip wc = WhereClip.All;
                if (!string.IsNullOrEmpty(startdate))
                {
                    wc = wc && V_CardExpense._.CreateDate >= startdate;
                }
                if (!string.IsNullOrEmpty(enddate))
                {
                    wc = wc && V_CardExpense._.CreateDate <= enddate;
                }
                List<V_CardExpense> list = SDDbSession.Default.From<V_CardExpense>().Where(wc).ToList();
                List<AccountHistory> items = new List<AccountHistory>();
                if (list != null)
                    foreach (var li in list)
                    {
                        AccountHistory ac = new AccountHistory();
                        ac.date = li.CreateDate.ToString();
                        ac.info = li.Value;
                        ac.memcardno = memcardno;
                        ac.transactionamount = li.Amount.ToString();
                        items.Add(ac);
                    }

                JavaScriptSerializer js = new JavaScriptSerializer();
                string json = js.Serialize(items);
                return "{\"status\":\"200\", \"result\":" + json + "}";
            }
            else if (s == "500")
            { return "{\"stutus\":\"500\"}"; }
            else
            { return "{\"stutus\":\"501\"}"; }
        }
        #endregion

        #region 车辆信息查询接口
        [WebMethod]
        public string VehicleQuery(string memcardno, string password)
        {
            MemberCarInfo car = new MemberCarInfo();
            string s = UserStatus(memcardno, password);
            if (s == "200")
            {
                V_MemCardInfoType minfo = SDDbSession.Default.From<V_MemCardInfoType>().Where(V_MemCardInfoType._.MemCardNo == memcardno).ToFirst();


                MemberCarInfo car1 = SDDbSession.Default.From<MemberCarInfo>().Where(MemberCarInfo._.Memcardno == memcardno).ToFirst();

                if (car != null)
                {
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    string json = js.Serialize(car);
                    return "{\"status\":\"200\", \"result\":" + json + "}";
                }
                else
                {
                    if (minfo != null)
                    {
                        car.Carplatenumber = minfo.CarNo;
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        string json = js.Serialize(car);
                        return "{\"status\":\"200\", \"result\":" + json + "}";
                    }
                    else
                        return "{\"status\":\"502\", \"result\":\"\"}";
                }
            }
            else if (s == "501")
            { return "{\"stutus\":\"501\"}"; }
            else
            { return "{\"stutus\":\"500\"}"; }
        }
        #endregion

        #region 位置信息上报
        [WebMethod]
        public string locationUpdate(string memcardno, string str)
        {
            if (!string.IsNullOrEmpty(str) && !string.IsNullOrEmpty(memcardno))
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                LocationUpdate lo = (LocationUpdate)js.Deserialize(str, typeof(LocationUpdate));
                List<locations> lists = lo.locationinfo;
                int result = 0;
                if (lists.Count > 0)
                {
                    foreach (locations l in lists)
                    {
                        Location item = new Location();
                        item.DeAttach();
                        item.Deviceid = lo.deviceid;
                        item.Memcardno = lo.memcardno;
                        item.Latitude = l.latitude;
                        item.Longitude = l.longitude;
                        item.Realtime = l.realtime;
                        result += SDDbSession.Default.Insert(item);
                    }
                }
                if (result > 0)
                {
                    return "{\"status\":\"200\", \"result\":\"\"}";
                }
                else
                {
                    return "{\"status\":\"202\", \"result\":\"添加数据失败！\"}";
                }
            }
            return "{\"status\":\"201\", \"result\":\"没有具体信息!\"}";
        }
        #endregion

        #region 添加用户 修改用户 删除用户
        public string UserCreate(webuser str)
        {
            string url = "http://127.0.0.1:5280/api/admin/ usercreate";

            JavaScriptSerializer js = new JavaScriptSerializer();
            string users = js.Serialize(str);
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(users);

            // Prepare web request...
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);

            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            // Get response
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
            string content = reader.ReadToEnd();
            myResponse.Close();
            return content;
        }
        #endregion

        #region 提交反馈
        [WebMethod]
        public string ReportFeedback(string memcardno, string password, string feedback)
        {
            string s = UserStatus(memcardno, password);
            if (s == "200")
            {
                AppFeedback back = new AppFeedback();
                back.DeAttach();
                back.Memcardno = memcardno;
                back.Feedback = feedback;
                SDDbSession.Default.Insert(back);
                return "{\"status\":\"200\", \"result\":\"\"}";
            }
            else
            { return "{\"stutus\":\"500\"}"; }
        }
        #endregion

        #region 提交异常
        [WebMethod]
        public string ReportError(string memcardno, string feedback)
        {
            try
            {
                AppException back = new AppException();
                back.DeAttach();
                back.Memcardno = memcardno;
                back.Stacktrace = feedback;
                SDDbSession.Default.Insert(back);
                return "{\"status\":\"200\", \"result\":\"\"}";
            }
            catch (Exception) { return "{\"status\":\"500\", \"result\":\"\"}"; }
        }
        #endregion

        #region 空车发布
        [WebMethod]
        public string VechiclePublish(string memcardno, string password, string carplatenumber, string toprovince, string tocity, string toregion, string fromprovince, string fromcity, string fromregion, string validdate, string invaliddate)
        {
            string s = UserStatus(memcardno, password);
            if (s == "200")
            {
                MemberCarInfo car = new MemberCarInfo();
                car.DeAttach();
                car.Carplatenumber = carplatenumber;
                car.Fromcity = fromcity;
                car.Fromprovince = fromprovince;
                car.Fromregion = fromregion;
                car.Invaliddate = invaliddate;
                car.Memcardno = memcardno;
                car.Tocity = tocity;
                car.Toprovince = toprovince;
                car.Toregion = toregion;
                car.Validdate = validdate;
                SDDbSession.Default.Insert(car);
                return "{\"status\":\"200\", \"result\":\"\"}";
            }
            else if (s == "501")
            { return "{\"stutus\":\"501\"}"; }
            else
            { return "{\"stutus\":\"500\"}"; }
        }
        #endregion

        #region 推送自动匹配
        public string MsgPush(msgpush str)
        {
            string url = "http://127.0.0.1:5280/api/admin/msgpush";

            JavaScriptSerializer js = new JavaScriptSerializer();
            string users = js.Serialize(str);
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(users);

            // Prepare web request...
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);

            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            // Get response
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
            string content = reader.ReadToEnd();
            myResponse.Close();
            return content;
        }
        #endregion
    }
}
